﻿
//debugger;
// actionFlag: 1 -> 新增；2 -> 修改；3 -> 查看
var actionFlag = getPar1("actionFlag");
var const_UserId = parent.parent._currentUserID;
var const_UserName = parent.parent._currentUserName;

$(document).ready(function () {
    if (actionFlag == 1) {
        obj = $("#SystemGenNo");
        genNewSequenceNo(obj, "PurchaseNo");

        $("#AddUserName").val(const_UserName);
        $("#OrderNo").focus();
        
    }

    if (actionFlag == 0) {

    }
    $("#OrderNo").bind("change", function () { var poNo = $(this).val().toUpperCase(); fnCheckOrderNo(poNo); });
});


// 检测采购订单编号是否重复
var fnCheckOrderNo = function (val) {
    if (val != "") {
        var orderNo = fnGetData("V_BH_PurchaseOrder", "ID<>'" + instance[0].ID.toString() + "' and OrderNo='" + val + "'");
        if (orderNo != null && orderNo != "") {
            alert("采购订单编号: [ " + val + " ] 已存在, 请重新输入!");
            setTimeout(function () {
                $("#OrderNo").focus();
                $("#OrderNo").val("");
            }, 10);
        }
    }
}

var getCompanyData = function (company) {
    return fnGetData("BH_Company", "CompanyNo='" + company + "' or CompanyName='" + company + "' or ShortName='" + company + "'");
}

// 设置供应商名称
var setCompanyName = function () {
    var companyNo = $("#VendorNo").attr("SValue");
    Company = getCompanyData(companyNo);

    if (Company == null || Company == "") {
        alert("供应商：" + companyNo + " 还未定义!");
        $("#VendorName").val("");
        $("#VendorNo").focus();
        return;
    }
    
    $("#VendorName").val(Company.rows[0].CompanyName);
}

// 明细表新增行
var fnCustomeRowAddEvent = function (trs, i) {
    _DataTable.Rows[i].ID = "00000000-0000-0000-0000-000000000000";
    setLineNo();

    var singleWeightObj = trs.find("input[name='SingleWeight']");
    singleWeightObj.numberbox({
        precision: 2
    });
    singleWeightObj.val("0.00");
    singleWeightObj.bind("change", function () { var o = trs; calcWeight(o); });

    var qtyObj = trs.find("input[name='Qty']");
    qtyObj.numberbox({
        precision: 2
    });
    qtyObj.val("0.00");
    qtyObj.bind("change", function () { var o = trs; calcWeight(o); });

    var weightObj = trs.find("input[name='Weight']");
    weightObj.numberbox({
        /*min: -999,*/
        precision: 2
    });
    weightObj.val("0.00");
    weightObj.bind("change", function () { var o = trs; calcAmount(o); calcTotalWeightAndAmount(); });

    var priceObj = trs.find("input[name='StandPrice']");
    priceObj.numberbox({
        /*min: -999,*/
        precision: 2
    });
    priceObj.val("0.00");
    priceObj.bind("change", function () { var o = trs; calcAmount(o); calcTotalWeightAndAmount(); });

    var o = trs.find("input[name='ItemNo']");
    o.bind("change", function () { var t = $(this).val(); var o = trs; setItemDetail(t, o); });
    o.focus();
    o.click();

    trs.find("input[name='Amount']").val("0.00");
}

// 单件重量与件数输入时计算重量并同时计算合计金额与合计重量
var calcWeight = function (o) {
    singleWeight = parseFloat(o.find("input[name='SingleWeight']").val());
    qty = parseFloat(o.find("input[name='Qty']").val());

    o.find("input[name='Weight']").val((singleWeight * qty).toFixed(2));

    calcAmount(o);
    calcTotalWeightAndAmount();
}

// 单价与重量输入时计算合计金额与合计重量
var calcTotalWeightAndAmount = function () {
    var trs = $("#Details tbody tr");
    if (trs.length >= 1) {
        var weightTotal = 0;
        var amountTotal = 0;
        trs.each(function (em) {
            weightTotal = weightTotal + parseFloat($(trs[em]).find("input[name='Weight']").val().toString());
            amountTotal = amountTotal + $(trs[em]).find("input[name='Weight']").val() * $(trs[em]).find("input[name='StandPrice']").val();
        });
    }
    $("#TotalWeight").val(weightTotal.toFixed(2));
    $("#TotalAmount").val(amountTotal.toFixed(2));
}

// 明细表当前行单价或重量改变时计算金额
var calcAmount = function (o) {
    o.find("input[name='Amount']").val((o.find("input[name='Weight']").val() * o.find("input[name='StandPrice']").val()).toFixed(2));
}

// 明细表删除记录时重新计算LineNo
var fnCustomeRowDelEvent = function () {
    setLineNo();
}

var customSetEvent = function () {
    if (actionFlag == "2") {
        var now = new Date();
        parent.setAddNewButtonHiden();
        //debugger;
        var trs = $("#Details tbody tr");
        if (trs.length >= 1) {
            trs.each(function (em) {
                $(trs[em]).find("input[name='ItemNo']").attr("disabled", "disabled");
                $(trs[em]).find("input[name='StandPrice']").attr("disabled", "disabled");
                $(trs[em]).find("input[name='Weight']").attr("disabled", "disabled");
                $(trs[em]).find("input[name='SingleWeight']").attr("disabled", "disabled");
                $(trs[em]).find("input[name='Qty']").attr("disabled", "disabled");
            });
        }
    }
}

var setLineNo = function () {
    var trs = $("#Details tbody tr");
    if (trs.length >= 1) {
        var seq = 1;
        trs.each(function (em) {
            $(trs[em]).find("input[name='LineNo']").val(seq.toString());
            seq = seq + 1;
        });
    }
}

var getItemData = function (item) {
    return fnGetData("BH_ItemMaster", "ItemNo='" + item + "' or ItemModel='" + item + "' or ItemName='" + item + "'");
}

var setItemDetail = function (itemNo, o) {
    if (itemNo != "" && itemNo != null) {
        ItemDetail = getItemData(itemNo);

        if (ItemDetail == null || ItemDetail == "") {
            alert("物料：" + itemNo + " 还未定义!");
            o.find("input[name='ItemNo']").val("");
            o.find("input[name='ItemModel']").val("");
            o.find("input[name='ItemName']").val("");
            setTimeout(function () {
                o.find("input[name='ItemNo']").focus();
            }, 10);
            return;
        }

        if (ItemDetail.rows[0].ItemType != "P") {
            alert("物料：" + itemNo + " 物料类型不是原材料!");
            o.find("input[name='ItemNo']").val("");
            o.find("input[name='ItemModel']").val("");
            o.find("input[name='ItemName']").val("");
            setTimeout(function () {
                o.find("input[name='ItemNo']").focus();
            }, 10);
            return;
        }

        o.find("input[name='ItemNo']").val(ItemDetail.rows[0].ItemNo);
        o.find("input[name='ItemModel']").val(ItemDetail.rows[0].ItemModel);
        o.find("input[name='ItemName']").val(ItemDetail.rows[0].ItemName);
    }
}


// 提交检测
var fnCustomCheck = function () {
    if (instance[0].OrderNo == "" || instance[0].OrderNo == null) {
        $('#OrderNo').focus();
        return "采购订单编号不能为空!";
    }
    if (instance[0].VendorNo == "" || instance[0].VendorNo == null) {
        $('#VendorNo').focus();
        return "供应商不能为空!";
    }
    if (instance[0].OrderDate == "" || instance[0].OrderDate == null) {
        $('#OrderDate').focus();
        return "订单日期不能为空!";
    }

    return "";
}

// 检测明细表中的记录是否录入
var fnCheckDetail = function () {
    var trs = $("#Details tbody tr");
    var errorFlag = 0;

    if (trs.length < 1) {
        alert("订单部品列表中不存在任何部品!");
        return false;
    }

    trs.each(function (em) {
        var itemNo = $(trs[em]).find("input[name='ItemNo']");
        var standPrice = $(trs[em]).find("input[name='standPrice']");
        var weight = $(trs[em]).find("input[name='Weight']");

        if (itemNo.val() == "") {
            alert("订单部品列表中的部品编号不能为空!");
            itemNo.focus();
            errorFlag = 1;
            return false;
        }

        if (parseFloat(standPrice.val().toString()) == 0) {
            alert("订单部品列表中的部品单价不能为0!");
            standPrice.focus();
            errorFlag = 1;
            return false;
        }

        if (parseFloat(weight.val().toString()) == 0) {
            alert("订单部品列表中的重量不能为0!");
            weight.focus();
            errorFlag = 1;
            return false;
        }
    });

    if (errorFlag == 1) {
        return false;
    }

    return true;
}

var fnSetValue = function () {
    instance[0].OrderNo = instance[0].OrderNo.toUpperCase();
    instance[0].AddUser = const_UserId;
    if (actionFlag == "1") {
        var now = new Date();
        instance[0].AddTime = fnGetMyDate(now).toString();
    }
}

// 保存数据
var fnCustomSave = function () {
    if (fnCheckDetail() == false) {
        return;
    }

    fnSetValue();

    dataAction = (actionFlag == "1") ? "A" : "C";

    if (typeof (_DataTable) != "undefined") {
        if (fnCheckEmpty() == false) {
            alert("明细数据没有录入");
        }
        _DataTable.GetData();

        detailJson = $.toJSON(_DataTable.Rows).replace(/'/g, "[B]").replace(/\+/g, "[J]")
    }

    json = $.toJSON(instance[0]).replace(/'/g, "[B]").replace(/\+/g, "[J]");
    //debugger;
    $.ajax({
        async: false, //异步请求
        cache: false, //不从浏览器缓存中加载
        type: "GET",
        /*dataType: "json",*/
        url: "/DCBH/DCBHCommonOperator.aspx",
        data: { Action: "procedure", entity: "V_BH_PurchaseOrder", json: json, detailJson: detailJson, dataAction: dataAction },
        success: function (data) {
            //debugger;
            if (data != "") {
                if (data == "1") {
                    alert("数据保存成功!");

                    if (parent.SaveAndAddNewFlag == true) {
                        location.href = location.href
                    }

                    if (parent.SaveSuccessClose == true) {
                        parent.parent.CloseCurPage();
                    }
                }
                else {
                    alert(data);
                }
            }
        },
        error: function (e) {
            alert("保存失败, 请联系开发人员，核查系统！");
            return;
        }
    });

} 